/**
 * PokerMind 前端位置计算优化
 * 支持前端上传位置信息，提升API性能
 * 
 * @author PokerMind Team
 */

// 位置计算工具类
class PokerPositionCalculator {
    
    // 位置常量
    static POSITIONS = {
        6: ['BTN', 'SB', 'BB', 'UTG', 'MP', 'CO'],
        5: ['BTN', 'SB', 'BB', 'UTG', 'CO'],
        4: ['BTN', 'SB', 'BB', 'UTG'],
        3: ['BTN', 'SB', 'BB'],
        2: ['BTN', 'BB']  // 两人桌特殊情况
    };
    
    /**
     * 计算玩家位置
     * @param {number} playerSeat - 玩家座位号 (1-based)
     * @param {number} buttonSeat - Button座位号 (1-based)
     * @param {number} totalPlayers - 总玩家数
     * @returns {string} 位置名称 (BTN/SB/BB/UTG/MP/CO)
     */
    static calculatePlayerPosition(playerSeat, buttonSeat, totalPlayers) {
        if (!this.POSITIONS[totalPlayers]) {
            console.warn(`Unsupported table size: ${totalPlayers} players`);
            return 'UNKNOWN';
        }
        
        const relativeSeat = (playerSeat - buttonSeat + totalPlayers) % totalPlayers;
        return this.POSITIONS[totalPlayers][relativeSeat] || 'UNKNOWN';
    }
    
    /**
     * 计算行动顺序
     * @param {number} playerSeat - 玩家座位号
     * @param {number} buttonSeat - Button座位号
     * @param {number} totalPlayers - 总玩家数
     * @returns {number|null} 行动顺序 (1=first, null=可能不需要行动)
     */
    static calculateActionOrder(playerSeat, buttonSeat, totalPlayers) {
        if (totalPlayers === 2) {
            // 两人桌：Button(SB)先行动
            return playerSeat === buttonSeat ? 1 : 2;
        } else {
            // 多人桌：UTG开始行动
            const utgSeat = ((buttonSeat - 1) + 3) % totalPlayers + 1;
            
            if (playerSeat === utgSeat) {
                return 1; // UTG第一个行动
            }
            
            // BB位置可能不需要行动（如果没有加注）
            const bbSeat = ((buttonSeat - 1) + 2) % totalPlayers + 1;
            if (playerSeat === bbSeat) {
                return null; // BB可能不需要行动
            }
            
            // 计算相对行动顺序
            const relativeOrder = (playerSeat - utgSeat + totalPlayers) % totalPlayers;
            return relativeOrder === 0 ? 1 : relativeOrder + 1;
        }
    }
    
    /**
     * 为游戏数据添加位置信息
     * @param {Object} gameData - 游戏数据
     * @returns {Object} 增强后的游戏数据
     */
    static enrichGameData(gameData) {
        const { buttonSeat, players } = gameData;
        const totalPlayers = players.length;
        
        const enrichedPlayers = players.map(player => ({
            ...player,
            position: this.calculatePlayerPosition(player.seatNumber, buttonSeat, totalPlayers),
            actionOrder: this.calculateActionOrder(player.seatNumber, buttonSeat, totalPlayers)
        }));
        
        return {
            ...gameData,
            players: enrichedPlayers
        };
    }
}

// API调用示例
class PokerMindAPI {
    
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
    }
    
    /**
     * 创建手牌 - 优化版（包含位置信息）
     * @param {Object} gameData - 游戏数据
     * @returns {Promise<Object>} API响应
     */
    async createHand(gameData) {
        // 前端预处理：添加位置信息
        const optimizedRequest = PokerPositionCalculator.enrichGameData(gameData);
        
        console.log('📤 发送优化请求（包含位置信息）:', {
            handId: optimizedRequest.handId,
            positions: optimizedRequest.players.map(p => ({
                seat: p.seatNumber,
                position: p.position,
                actionOrder: p.actionOrder
            }))
        });
        
        try {
            const response = await fetch(`${this.baseUrl}/api/hands/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(optimizedRequest)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const result = await response.json();
            
            console.log('📥 服务端响应:', {
                success: result.success,
                heroPosition: result.data?.hero_position,
                nextActionSeat: result.data?.next_action_seat,
                currentPot: result.data?.current_pot
            });
            
            return result;
            
        } catch (error) {
            console.error('❌ 创建手牌失败:', error);
            throw error;
        }
    }
    
    /**
     * 创建手牌 - 兼容版（无位置信息，服务端计算）
     * 用于对比性能差异
     */
    async createHandLegacy(gameData) {
        // 移除位置信息，让服务端计算
        const legacyRequest = {
            ...gameData,
            players: gameData.players.map(({ position, actionOrder, ...player }) => player)
        };
        
        console.log('📤 发送传统请求（无位置信息）');
        
        const response = await fetch(`${this.baseUrl}/api/hands/create`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(legacyRequest)
        });
        
        return response.json();
    }
}

// 使用示例
async function demonstratePositionOptimization() {
    const api = new PokerMindAPI('http://localhost:8080');
    
    // 模拟游戏数据
    const gameData = {
        hand_id: `DEMO_${Date.now()}`,
        table_id: "NL200_6MAX_DEMO",
        button_seat: 1,
        small_blind: 100.0,
        big_blind: 200.0,
        ante: 0,
        players: [
            {
                player_id: "btn_player_001",
                seat_number: 1,
                player_name: "ButtonPlayer",
                stack: 20000.0,
                is_hero: false
            },
            {
                player_id: "sb_player_002", 
                seat_number: 2,
                player_name: "SmallBlind",
                stack: 19500.0,
                is_hero: false
            },
            {
                player_id: "hero_player_999",
                seat_number: 3,
                player_name: "HeroPlayer",
                stack: 18500.0,
                is_hero: true,
                hole_cards: ["As", "Kh"]
            },
            {
                player_id: "utg_player_003",
                seat_number: 4, 
                player_name: "UTGPlayer",
                stack: 21000.0,
                is_hero: false
            },
            {
                player_id: "mp_player_004",
                seat_number: 5,
                player_name: "MiddlePosition", 
                stack: 17800.0,
                is_hero: false
            },
            {
                player_id: "co_player_005",
                seat_number: 6,
                player_name: "CutOff",
                stack: 22500.0,
                is_hero: false
            }
        ]
    };
    
    console.log('🎯 德州扑克位置优化演示');
    console.log('=====================================');
    
    // 演示前端位置计算
    const enrichedData = PokerPositionCalculator.enrichGameData(gameData);
    console.log('💡 前端计算结果:');
    enrichedData.players.forEach(player => {
        console.log(`  座位${player.seat_number} → ${player.position} (行动顺序: ${player.actionOrder || 'N/A'})`);
    });
    
    try {
        // 性能对比测试
        console.log('\n⚡ 性能对比测试:');
        
        // 优化版本（包含位置）
        const startTime1 = performance.now();
        const optimizedResult = await api.createHand(gameData);
        const endTime1 = performance.now();
        
        console.log(`✅ 优化版本耗时: ${(endTime1 - startTime1).toFixed(2)}ms`);
        console.log(`   Hero位置: ${optimizedResult.data.hero_position}`);
        console.log(`   下个行动: 座位${optimizedResult.data.next_action_seat}`);
        
        // 传统版本（服务端计算）
        gameData.hand_id = `DEMO_LEGACY_${Date.now()}`; // 避免重复
        const startTime2 = performance.now();
        const legacyResult = await api.createHandLegacy(gameData);
        const endTime2 = performance.now();
        
        console.log(`📊 传统版本耗时: ${(endTime2 - startTime2).toFixed(2)}ms`);
        console.log(`   结果一致性: ${optimizedResult.data.hero_position === legacyResult.data.hero_position ? '✅' : '❌'}`);
        
        const improvement = ((endTime2 - endTime1) / endTime2 * 100).toFixed(1);
        console.log(`🚀 性能提升: ${improvement}%`);
        
    } catch (error) {
        console.error('演示失败:', error.message);
    }
}

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        PokerPositionCalculator,
        PokerMindAPI,
        demonstratePositionOptimization
    };
}

// 浏览器环境自动演示
if (typeof window !== 'undefined') {
    // 页面加载后执行演示
    document.addEventListener('DOMContentLoaded', () => {
        const demoButton = document.getElementById('demo-position-optimization');
        if (demoButton) {
            demoButton.addEventListener('click', demonstratePositionOptimization);
        }
    });
}

